package com.summer.shopping.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.summer.shopping.domain.table.dto.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.summer.shopping.domain.table.Product;
import com.summer.shopping.domain.table.dto.ProductQueryParam;
import com.summer.shopping.domain.table.vo.ProductPageVo;
import com.summer.shopping.service.ProductService;
import com.summer.shopping.mapper.ProductMapper;
import com.summer.shopping.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;

/**
* @author 86136
* @description 针对表【product(商品表)】的数据库操作Service实现
* @createDate 2025-06-20 13:57:18
*/
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService{

    @Autowired
    private ProductMapper productMapper;
    @Override
    public PageResult pageQuery(PageDTO pageDTO, ProductQueryParam param) {
        //设定排序字段
        Page<Product> productPage = new Page<>(pageDTO.getPageNo(), pageDTO.getPageSize());
        OrderItem orderItem = new OrderItem().setAsc(false).setColumn("create_time");
        productPage.addOrder(orderItem);
        //设置查询字段
        List<String> list = List.of(new String[]{"id","name","descriptions","price","img","create_time","numbers"});
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<Product>().select(list);
        //添加条件
        if(BeanUtil.isNotEmpty(param)){
            if(param.getSecondaryCategoryId()!=null){
                productQueryWrapper.eq("secondary_category_id",param.getSecondaryCategoryId());
            }
            if(param.getName()!=null&&param.getName().length()!=0){
                productQueryWrapper.like("name",param.getName());
            }
        }
        //查询
        Page<Product> productPage1 = productMapper.selectPage(productPage, productQueryWrapper);
        //封装VO
        List<Product> records = productPage1.getRecords();
        long total = productPage1.getTotal();
        List<ProductPageVo> productPageVos = new ArrayList<>();
        for (Product product: records) {
            productPageVos.add(BeanUtil.copyProperties(product, ProductPageVo.class));
        }

        PageResult<ProductPageVo> productPageVoPageResult = new PageResult<ProductPageVo>();
        //封装统一分页查询返回对象
        productPageVoPageResult.setRecords(productPageVos);
        productPageVoPageResult.setTotal(total);

        return productPageVoPageResult;
    }
}




